/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.designschema.synchronization;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.service.MetadataService;
import com.inspur.edp.web.common.metadata.MetadataGetterParameter;
import com.inspur.edp.web.common.metadata.MetadataTypeEnum;
import com.inspur.edp.web.common.metadata.MetadataUtility;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.designschema.elements.Schema;
import com.inspur.edp.web.designschema.synchronization.helplinkconfig.VoMetadataHelpLinkConfigModifierBeforeSaving;
import com.inspur.edp.web.formmetadata.metadata.FormMetadataContent;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.List;

public class FormMetadataUpdate {
    public static void update(GspMetadata formMetadata) {
        FormMetadataContent content = (FormMetadataContent) ((formMetadata.getContent() instanceof FormMetadataContent) ? formMetadata.getContent() : null);
        if (content == null) {
            return;
        }
        String formContent = SerializeUtility.getInstance().serialize(content.getContents());
        JsonNode formObject = null;

        String formString = (formContent instanceof String) ? formContent : null;
        formObject = SerializeUtility.getInstance().toJsonNode(formString);

        JsonNode schemas = null;
        JsonNode jsonNodeModules = formObject.get("module");
        if (jsonNodeModules != null) {
            schemas = jsonNodeModules.get("schemas");
        }

        if (schemas != null) {
            String schemasString = schemas.toString();

            List<Schema> schemaList = SerializeUtility.getInstance().deserialize(schemasString, new TypeReference<List<Schema>>() {
            });
            Synchronizer synchronizer = new Synchronizer();
            for (Schema schema : schemaList) {
                if ("vo".equals(schema.getSourceType())) {
                    String voPath = StringUtility.getOrDefault(schema.getVoPath(), formMetadata.getRelativePath());
                    String voNameSpace = StringUtility.getOrDefault(schema.getVoNameSpace(), formMetadata.getHeader().getNameSpace());
                    MetadataGetterParameter metadataGetterParameter = MetadataGetterParameter.getNewInstance(schema.getId(), voPath, MetadataTypeEnum.ViewModel);
                    metadataGetterParameter.setTargetMetadataCode(schema.getCode());
                    metadataGetterParameter.setTargetMetadataName(schema.getName());
                    metadataGetterParameter.setTargetMetadataNamespace(voNameSpace);
                    metadataGetterParameter.setTargetMetadataNotFoundMessage("根据表单元数据获取VO元数据为空，请检查表单元数据module>schemas>id 是否正确，此参数为表单对应VO元数据id参数！");
                    GspMetadata metadata = MetadataUtility.getInstance().getMetadataWithDesign(metadataGetterParameter);

                    GspViewModel viewObject = (GspViewModel) ((metadata.getContent() instanceof GspViewModel) ? metadata.getContent() : null);
                    metadata.setContent(synchronizer.synchronize(formObject, schema, viewObject));

                    // 执行元数据保存前参数处理 action
                    VoMetadataHelpLinkConfigModifierBeforeSaving.modify(metadata);

                    MetadataService service = SpringBeanUtils.getBean(MetadataService.class);
                    service.saveMetadata(metadata, metadata.getRelativePath() + "/" + metadata.getHeader().getFileName());
                }
            }
        } else {
            throw new RuntimeException("表单DOM结构错误：未到module.schemas节点");
        }
    }
}
